package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;


@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {
    @GetMapping("/sentinel01")
    public String doSentinel01(){
        return "<a href=''/>百度";
    }
    @GetMapping("/sentinel02")
    public String doSentinel02(){
        return "sentinel 02 test  ...";
    }

    @Autowired
    private ResourceService resourceService;
    @GetMapping("/sentinel03")
    public String doSentinel03() throws InterruptedException {
        //resourceService.doGetResource();

        //return "sentinel 03 test";
        return resourceService.doGetResource();
    }

    @GetMapping("/sentinel04")
    public String doSentinel04() throws InterruptedException {
        resourceService.doGetResource();
        return "sentinel 04 test";
    }

    //AtomicLong 类支持线程安全的自增自减操作
    private AtomicLong atomicLong=new AtomicLong(1);
    @GetMapping("/sentinel05")
    public  String doSentinel05() throws InterruptedException {
        //获取自增对象的值,然后再加1
        long num=atomicLong.getAndIncrement();//先取值，再加1
        if(num%2==0){//模拟50%的慢调用比例
            Thread.sleep(200);//模拟耗时操作
            //throw new RuntimeException("exception ....");
        }
        return "sentinel 05 test";
    }

    @GetMapping("/sentinel/findById")
    //@SentinelResource("selectByid")
    public String doFindById(@RequestParam("id") Integer id){
        return resourceService.doGetResource(id);
        //return "resource id is "+id;
    }
}
